<template>
  <PublicLoading v-if="loading.mounted" />
  <div v-else class="dt-main-tabs-content">
    <div class="dt-content-main">
      <div class="dt-content-head">
        <div class="dt-content-head-tab">
          <div class="dt-head-title">
            <!-- <div class="dt-head-breadcrumb" @click="goCreatePm">
              <i class="el-icon-arrow-left"></i>
              <span>返回</span>
              <em>|</em>
            </div> -->
            <span>设置组织架构</span>
          </div>
        </div>
      </div>
      <div class="dt-content-page">
        <div class="dt-org" v-if="org">
          <PmComOrgTree :nodes="org" @createCommand="createCommand" @editCommand="editCommand" @toogleSlide="toogleSlide"
            @toogleChildrenSlide="toogleChildrenSlide" @showTask="showTask" />
        </div>
      </div>
      <div class="dt-content-bottom">
        <el-button type="primary" size="medium" @click="goCreateNode">设置项目节点</el-button>
        <el-button size="medium" @click="goCreatePm">返回上一步</el-button>
      </div>
    </div>
    <el-drawer title="生产任务统计" :visible.sync="dialogVisible.task" direction="rtl" size="70%" :append-to-body="true">
      <div class="dt-el-drawer">
        <span>任务总数：{{task.totalCount}}</span><span>进行中：{{task.doingCount}}</span><span>已完成：{{task.complateCount}}</span><span>待认领：{{task.waitCount}}</span><span>已延期：{{task.delayCount}}</span>
        <em>|</em><span>总产值：{{task.showOutput?(task.totalOutput||'0'):'***'}}
          元</span>
      </div>
      <div class="dt-drawer-table">
        <el-table :data="task.list" border :row-class-name="tableRowClassName">
          <el-table-column prop="taskNo" label="编号"></el-table-column>
          <el-table-column prop="nodeName" label="项目节点"></el-table-column>
          <el-table-column prop="majorName" label="所属专业"></el-table-column>
          <el-table-column prop="taskName" label="任务名称"></el-table-column>
          <el-table-column prop="taskStateName" label="任务状态"></el-table-column>
          <el-table-column prop="taskTypeName" label="任务类型"></el-table-column>
          <el-table-column prop="createName" label="创建人"></el-table-column>
          <el-table-column prop="masterName" label="负责人"></el-table-column>
          <el-table-column label="产值">
            <template slot-scope="scope">
              {{task.showOutput?(scope.row.output||'0'):'***'}} 元
            </template>
          </el-table-column>
          <el-table-column label="计划工期">
            <template slot-scope="scope">
              {{scope.row.startTime|filterDate}}至{{scope.row.endTime|filterDate}}
            </template>
          </el-table-column>
          <el-table-column prop="planDays" label="计划天数（天）"></el-table-column>
          <el-table-column label="完成时间">
            <template v-if="scope.row.completeTime" slot-scope="scope">{{scope.row.completeTime|filterDate}}</template>
          </el-table-column>
          <el-table-column prop="consumeDays" label="工期消耗（天）"></el-table-column>
          <el-table-column label="完成情况">
            <template slot-scope="scope">
              {{scope.row.completeState|filterComState}}
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination @current-change="handleCurrentChange" :current-page.sync="currentPage" :page-size="20" layout="prev, pager, next, jumper"
        :total="task.totalCount">
      </el-pagination>
    </el-drawer>
    <el-dialog :title="managerForm.isEdit?'编辑管理单位':'添加管理单位'" :visible.sync="dialogVisible.manager" width="680px" :close-on-click-modal="false"
      :append-to-body="true" @close="quit('manager')">
      <el-form :model="managerForm" :rules="managerRules" ref="managerForm" label-width="100px" :validate-on-rule-change="false">
        <el-form-item label="单位名称" prop="manageUnitName" size="medium">
          <el-input placeholder="请输入管理单位名称" v-model="managerForm.manageUnitName" maxlength="20"></el-input>
        </el-form-item>
        <el-form-item label="产值" prop="output" size="medium">
          <el-input placeholder="请输入产值" v-model="managerForm.output" maxlength="20" @input="outputInput($event,'0')"><template
              slot="append">元</template></el-input>
          <div v-if="managerForm.output" class="dt-je-china poa">{{$tools.moneyLower(managerForm.output)}}</div>
        </el-form-item>
        <el-form-item label="" size="medium" style="margin:-12px 0px 8px 0">
          <span>上级剩余可分配产值{{$tools.moneyLower(managerForm.residueOutput)}}元</span>
        </el-form-item>
        <el-form-item label="负责人" prop="masterUid" size="medium">
          <!--团队成员、外部成员-->
          <PublicSelectCompanyUser :option="optManager" @select="selectUser($event,'manager')" ref="managerSelectUser" />
        </el-form-item>
        <el-form-item label="" size="medium" v-if="managerForm.isEdit">
          <el-button type="primary" @click="sureEdit('Manager')" :loading="loading.manager">确定</el-button>
          <el-button @click="quit('manager')">取消</el-button>
        </el-form-item>
        <el-form-item label="" size="medium" v-else>
          <el-button type="primary" @click="sureCreate('Manager')" :loading="loading.manager">确定</el-button>
          <el-button @click="quit('manager')">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog :title="cooperateForm.isEdit?'编辑合作单位':'添加合作单位'" :visible.sync="dialogVisible.cooperate" width="680px" :close-on-click-modal="false"
      :append-to-body="true" @close="quit('cooperate')">
      <el-form :model="cooperateForm" :rules="cooperateRules" ref="cooperateForm" label-width="100px" :validate-on-rule-change="false">
        <el-form-item label="单位名称" prop="cooperationUnitName" size="medium">
          <el-input placeholder="请输入合作单位名称" v-model="cooperateForm.cooperationUnitName" maxlength="20"></el-input>
        </el-form-item>
        <el-form-item label="产值" prop="output" size="medium">
          <el-input placeholder="请输入产值" v-model="cooperateForm.output" maxlength="20" @input="outputInput($event,'1')"><template
              slot="append">元</template></el-input>
          <div v-if="cooperateForm.output" class="dt-je-china poa">{{$tools.moneyLower(cooperateForm.output)}}</div>
        </el-form-item>
        <el-form-item label="" size="medium" style="margin:-12px 0px 8px 0">
          <span>上级剩余可分配产值{{$tools.moneyLower(cooperateForm.residueOutput)}}元</span>
        </el-form-item>
        <el-form-item label="负责人" prop="masterUid" size="medium">
          <!--团队成员、外部成员-->
          <PublicSelectCompanyUser :option="optCooprate" @select="selectUser($event,'cooperate')" ref="cooperateSelectUser" />
        </el-form-item>
        <el-form-item label="" size="medium" v-if="cooperateForm.isEdit">
          <el-button type="primary" @click="sureEdit('Cooperate')" :loading="loading.cooperate">确定</el-button>
          <el-button @click="quit('cooperate')">取消</el-button>
        </el-form-item>
        <el-form-item label="" size="medium" v-else>
          <el-button type="primary" @click="sureCreate('Cooperate')" :loading="loading.cooperate">确定</el-button>
          <el-button @click="quit('cooperate')">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog :title="majorForm.isEdit?'编辑专业':'添加专业'" :visible.sync="dialogVisible.major" width="680px" :close-on-click-modal="false"
      :append-to-body="true" @close="quit('major')">
      <el-form :model="majorForm" :rules="majorRules" ref="majorForm" label-width="100px" :validate-on-rule-change="false">
        <el-form-item label="专业名称" prop="majorName" size="medium">
          <el-input placeholder="请输入专业名称" v-model="majorForm.majorName" maxlength="20"></el-input>
        </el-form-item>
        <el-form-item label="产值" prop="output" size="medium">
          <el-input placeholder="请输入产值" v-model="majorForm.output" maxlength="20" @input="outputInput($event,'2')"><template
              slot="append">元</template></el-input>
          <div v-if="majorForm.output" class="dt-je-china poa">{{$tools.moneyLower(majorForm.output)}}</div>
        </el-form-item>
        <el-form-item label="" size="medium" style="margin:-12px 0px 8px 0">
          <span>上级剩余可分配产值{{$tools.moneyLower(majorForm.residueOutput)}}元</span>
        </el-form-item>
        <el-form-item label="负责人" prop="masterUid" size="medium">
          <!--团队成员、外部成员-->
          <PublicSelectCompanyUser :option="optMajorMaster" @select="selectUser($event,'majorMaster')" ref="majorMasterSelectUser" />
        </el-form-item>
        <el-form-item label="参与人" prop="participants" size="medium">
          <!--团队成员、外部成员-->
          <PublicSelectCompanyUser :option="optMajorParter" @select="selectUser($event,'majorParter')" ref="majorParterSelectUser" />
        </el-form-item>
        <el-form-item label="" size="medium" v-if="majorForm.isEdit">
          <el-button type="primary" @click="sureEdit('Major')" :loading="loading.major">确定</el-button>
          <el-button @click="quit('major')">取消</el-button>
        </el-form-item>
        <el-form-item label="" size="medium" v-else>
          <el-button type="primary" @click="sureCreate('Major')" :loading="loading.major">确定</el-button>
          <el-button @click="quit('major')">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      uid: this.$tools.getDecrypt(this.$store.state.uid), //用户id
      loading: {
        manager: false,
        cooperate: false,
        major: false,
        mounted: false
      },
      //基本树形数据
      org: null,
      //树组件回传参数
      command: null,
      dialogVisible: {
        task: false,
        manager: false,
        cooperate: false,
        major: false
      },
      //管理单位
      managerForm: {
        isEdit: false,
        manageUnitName: '',
        residueOutput: '',
        output: '',
        masterUid: ''
      },
      managerRules: {
        manageUnitName: [{ required: true, message: '请输入管理单位名称', trigger: 'blur' }],
        output: [
          { required: true, message: '请输入产值', trigger: 'blur' },
          { validator: this.validateOutput.bind(this, '0'), trigger: 'blur' }
        ],
        masterUid: [{ required: true, message: '请选择负责人', trigger: 'change' }]
      },
      //合作单位
      cooperateForm: {
        isEdit: false,
        cooperationUnitName: '',
        residueOutput: '',
        output: '',
        masterUid: ''
      },
      cooperateRules: {
        cooperationUnitName: [{ required: true, message: '请输入合作单位名称', trigger: 'blur' }],
        output: [
          { required: true, message: '请输入产值', trigger: 'blur' },
          { validator: this.validateOutput.bind(this, '1'), trigger: 'blur' }
        ],
        masterUid: [{ required: true, message: '请选择负责人', trigger: 'change' }]
      },
      //专业
      majorForm: {
        isEdit: false,
        majorName: '',
        residueOutput: '',
        output: '',
        masterUid: '',
        participants: ''
      },
      majorRules: {
        majorName: [{ required: true, message: '请输入专业名称', trigger: 'blur' }],
        output: [
          { required: true, message: '请输入产值', trigger: 'blur' },
          { validator: this.validateOutput.bind(this, '2'), trigger: 'blur' }
        ],
        masterUid: [{ required: true, message: '请选择负责人', trigger: 'change' }]
        // participants: [{ required: true, message: '请选择参与人', trigger: 'change' }]
      },
      //管理单位的选人配置
      optManager: {
        width: '540px',
        placeholder: '请选择负责人，最多设置1人',
        isMultiple: false, //是否多选
        maxSelect: 1, //单选忽略
        //已选的成员列表
        selectedUserList: [],
        //团队成员列表
        companyUserList: []
      },
      //合作单位的选人配置
      optCooprate: {
        width: '540px',
        placeholder: '请选择负责人，最多设置1人',
        isMultiple: false, //是否多选
        maxSelect: 1, //单选忽略
        //已选的成员列表
        selectedUserList: [],
        //团队成员列表
        companyUserList: []
      },
      //专业-负责人的选人配置
      optMajorMaster: {
        width: '540px',
        placeholder: '请选择负责人，最多设置3人',
        isMultiple: true, //是否多选
        maxSelect: 3, //单选忽略
        //已选的成员列表
        selectedUserList: [],
        //团队成员列表
        companyUserList: []
      },
      //专业-参与人的选人配置
      optMajorParter: {
        width: '540px',
        placeholder: '请选择参与人，最多设置10人',
        isMultiple: true, //是否多选
        maxSelect: 10, //单选忽略
        //已选的成员列表
        selectedUserList: [],
        //团队成员列表
        companyUserList: []
      },
      //任务列表
      task: {
        list: [],
        nodes: null,
        totalCount: 0,
        doingCount: 0,
        complateCount: 0,
        waitCount: 0,
        delayCount: 0,
        totalOutput: 0,
        showOutput: false //来自组织架构
      },
      currentPage: 1
    }
  },
  computed: {
    query() {
      return this.$tools.getQuery(this)
    },
    rootProjectId() {
      return this.$tools.getQuery(this).rootProjectId
    }
  },
  filters: {
    filterDate(val) {
      return val.substring(0, 10)
    },
    filterComState(val) {
      if (val > 0) {
        return '提前' + val + '天完成'
      } else if (val < 0) {
        return '延期' + Math.abs(val) + '天完成'
      } else {
        return '按时完成'
      }
    }
  },
  methods: {
    //blur验证产值
    validateOutput(type, rule, value, callback) {
      var reg = /^(([1-9]\d{0,8}(\.\d{1,2})?)|(0\.\d{1,2}))$/
      var forms = ['managerForm', 'cooperateForm', 'majorForm']
      if (!reg.test(this[forms[type]].output)) {
        callback(new Error('请输入正确的产值'))
      } else {
        var output = parseFloat(this[forms[type]].output),
          residueOutput = parseFloat(this[forms[type]].residueOutput)

        if (output > residueOutput) {
          callback(new Error('请输入剩余可分配产值以内的数字'))
        } else {
          callback()
        }
      }
    },
    //输入验证
    outputInput(value, type) {
      // let that = this
      // let forms = ['managerForm', 'cooperateForm', 'majorForm']
      // let regStrs = [
      //   ['^0(\\d+)$', '$1'],
      //   ['[^\\d\\.]+$', ''],
      //   ['\\.(\\d?)\\.+', '.$1'],
      //   ['^(\\d+\\.\\d{2}).+', '$1']
      // ]
      // for (let i = 0; i < regStrs.length; i++) {
      //   let reg = new RegExp(regStrs[i][0])
      //   this[forms[type]].output = this[forms[type]].output.replace(reg, regStrs[i][1])
      // }

      let that = this
      let forms = ['managerForm', 'cooperateForm', 'majorForm']
      let regStrs = [
        ['^0(\\d+)$', '$1'],
        ['[^\\d\\.]+$', ''],
        ['\\.(\\d?)\\.+', '.$1'],
        ['^(\\d+\\.\\d{2}).+', '$1']
      ]
      if (this[forms[type]].output.indexOf('.') < 0) {
        this[forms[type]].output = this[forms[type]].output.split('.')[0].substring(0, 9)
      } else if (this[forms[type]].output.split('.')[0].length > 9) {
        this[forms[type]].output =
          this[forms[type]].output.split('.')[0].substring(0, 9) +
          (this[forms[type]].output.split('.')[1] ? '.' + this[forms[type]].output.split('.')[1] : '')
      }

      for (let i = 0; i < regStrs.length; i++) {
        let reg = new RegExp(regStrs[i][0])
        that[forms[type]].output = that[forms[type]].output.replace(reg, regStrs[i][1])
        // console.log(value.replace(reg, regStrs[i][1]), i)
      }
    },
    //团队成员列表
    getCompanyUserList() {
      var data = [{ userId: this.uid }],
        domain = [this.$store.state.DOMAIN],
        path = ['/project/project/companyUserList'],
        dataAxios = this.$tools.getDataAxios(this, domain, path, data)
      Promise.all(dataAxios)
        .then((response) => {
          this.$tools.callbackAxios(this, response, (response) => {
            var data = response[0].data
            if (data.code === 200) {
              //各个团队成员列表赋值
              this.optManager.companyUserList = data.data
              this.optCooprate.companyUserList = data.data
              this.optMajorMaster.companyUserList = data.data
              this.optMajorParter.companyUserList = data.data
            } else {
              this.$message({
                message: data.message,
                type: 'warning',
                duration: '1000',
                onClose: () => {}
              })
            }
          })
        })
        .catch((error) => {})
    },
    //获取组织架构数据
    getOrg(rootProjectId) {
      var data = [{ userId: this.uid, rootProjectId: rootProjectId }],
        domain = [this.$store.state.DOMAIN],
        path = ['/project/structure/orgStructure'],
        dataAxios = this.$tools.getDataAxios(this, domain, path, data)
      Promise.all(dataAxios)
        .then((response) => {
          this.$tools.callbackAxios(this, response, (response) => {
            var data = response[0].data
            if (data.code === 200) {
              var org = data.data
              this.org = this.setOrg(org)
            } else {
              this.$message({
                message: data.message,
                type: 'warning',
                duration: '1000',
                onClose: () => {}
              })
            }
          })
        })
        .catch((error) => {})
    },
    //组织架构添加相关 字段
    setOrg(nodes) {
      function deepSet(node) {
        node.isSlide = false
        node.isChildrenSlide = false
        node.top = node.cardType === 5 ? 25 : 60
        if (node.children.length) {
          node.children.forEach((item) => {
            deepSet(item)
          })
        }
      }
      deepSet(nodes)
      return nodes
    },
    //添加管理单位、合作单位、专业弹窗
    createCommand(command) {
      //创建先获取本卡片剩余产值
      this.getResidueValue(command.currentProjectId)
      //子组件回传参数
      this.command = command
    },
    //编辑管理单位、合作单位、专业弹窗
    editCommand(command) {
      if (command.type === 'edit') {
        this.getCardInfo(command.currentProjectId)
      } else if (command.type === 'delete') {
        this.$confirm('确定删除吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.deleteCard(command.currentProjectId)
          })
          .catch(() => {})
      }
      this.command = command
    },
    //管理单位、合作单位、专业选人后回调
    selectUser(ids, type) {
      console.log(ids, type)
      switch (type) {
        case 'manager':
          this.managerForm.masterUid = ids
          break
        case 'cooperate':
          this.cooperateForm.masterUid = ids
          break
        case 'majorMaster':
          this.majorForm.masterUid = ids
          break
        case 'majorParter':
          this.majorForm.participants = ids
          break
      }
    },
    //确认创建
    sureCreate(type) {
      this.$refs[type.toLowerCase() + 'Form'].validate((valid) => {
        if (valid) {
          this['create' + type]()
        }
      })
    },
    //确认编辑
    sureEdit(type) {
      this.$refs[type.toLowerCase() + 'Form'].validate((valid) => {
        if (valid) {
          this['edit' + type]()
        }
      })
    },
    //取消创建/编辑
    quit(type) {
      this.closeForm(type)
    },
    //重置表单和选人组件
    closeForm(type) {
      this.dialogVisible[type] = false
      this.$nextTick(() => {
        this.$refs[type + 'Form'].clearValidate()
      })
    },
    //创建管理单位
    createManager() {
      var data = [
          {
            userId: this.uid,
            rootProjectId: this.rootProjectId,
            currentProjectId: this.command.currentProjectId,
            manageUnitName: this.managerForm.manageUnitName,
            output: this.managerForm.output,
            masterUid: this.managerForm.masterUid
          }
        ],
        domain = [this.$store.state.DOMAIN],
        path = ['/project/structure/createManageUnit'],
        dataAxios = this.$tools.getDataAxios(this, domain, path, data)
      Promise.all(dataAxios)
        .then((response) => {
          this.$tools.callbackAxios(this, response, (response) => {
            var data = response[0].data
            if (data.code === 200) {
              this.$message({
                message: data.message,
                type: 'success',
                duration: '1000',
                onClose: () => {
                  this.loading.manager = false
                  this.dialogVisible.manager = false
                  var org = data.data
                  this.org = this.setOrg(org)
                }
              })
            } else {
              this.$message({
                message: data.message,
                type: 'warning',
                duration: '1000',
                onClose: () => {
                  this.loading.manager = false
                }
              })
            }
          })
        })
        .catch((error) => {})
    },
    //编辑管理单位
    editManager() {
      var data = [
          {
            userId: this.uid,
            rootProjectId: this.rootProjectId,
            currentProjectId: this.command.currentProjectId,
            manageUnitName: this.managerForm.manageUnitName,
            output: this.managerForm.output,
            masterUid: this.managerForm.masterUid
          }
        ],
        domain = [this.$store.state.DOMAIN],
        path = ['/project/structure/editManageUnit'],
        dataAxios = this.$tools.getDataAxios(this, domain, path, data)
      Promise.all(dataAxios)
        .then((response) => {
          this.$tools.callbackAxios(this, response, (response) => {
            var data = response[0].data
            if (data.code === 200) {
              this.$message({
                message: data.message,
                type: 'success',
                duration: '1000',
                onClose: () => {
                  this.loading.manager = false
                  this.dialogVisible.manager = false
                  var org = data.data
                  this.org = this.setOrg(org)
                }
              })
            } else {
              this.$message({
                message: data.message,
                type: 'warning',
                duration: '1000',
                onClose: () => {
                  this.loading.manager = false
                }
              })
            }
          })
        })
        .catch((error) => {})
    },
    //创建合作单位
    createCooperate() {
      var data = [
          {
            userId: this.uid,
            rootProjectId: this.rootProjectId,
            currentProjectId: this.command.currentProjectId,
            cooperationUnitName: this.cooperateForm.cooperationUnitName,
            output: this.cooperateForm.output,
            masterUid: this.cooperateForm.masterUid
          }
        ],
        domain = [this.$store.state.DOMAIN],
        path = ['/project/structure/createCooperationUnit'],
        dataAxios = this.$tools.getDataAxios(this, domain, path, data)
      Promise.all(dataAxios)
        .then((response) => {
          this.$tools.callbackAxios(this, response, (response) => {
            var data = response[0].data
            if (data.code === 200) {
              this.$message({
                message: data.message,
                type: 'success',
                duration: '1000',
                onClose: () => {
                  this.loading.cooperate = false
                  this.dialogVisible.cooperate = false
                  var org = data.data
                  this.org = this.setOrg(org)
                }
              })
            } else {
              this.$message({
                message: data.message,
                type: 'warning',
                duration: '1000',
                onClose: () => {
                  this.loading.cooperate = false
                }
              })
            }
          })
        })
        .catch((error) => {})
    },
    //编辑合作单位
    editCooperate() {
      var data = [
          {
            userId: this.uid,
            rootProjectId: this.rootProjectId,
            currentProjectId: this.command.currentProjectId,
            cooperationUnitName: this.cooperateForm.cooperationUnitName,
            output: this.cooperateForm.output,
            masterUid: this.cooperateForm.masterUid
          }
        ],
        domain = [this.$store.state.DOMAIN],
        path = ['/project/structure/editCooperationUnit'],
        dataAxios = this.$tools.getDataAxios(this, domain, path, data)
      Promise.all(dataAxios)
        .then((response) => {
          this.$tools.callbackAxios(this, response, (response) => {
            var data = response[0].data
            if (data.code === 200) {
              this.$message({
                message: data.message,
                type: 'success',
                duration: '1000',
                onClose: () => {
                  this.loading.cooperate = false
                  this.dialogVisible.cooperate = false
                  var org = data.data
                  this.org = this.setOrg(org)
                }
              })
            } else {
              this.$message({
                message: data.message,
                type: 'warning',
                duration: '1000',
                onClose: () => {
                  this.loading.cooperate = false
                }
              })
            }
          })
        })
        .catch((error) => {})
    },
    //创建专业
    createMajor() {
      var data = [
          {
            userId: this.uid,
            rootProjectId: this.rootProjectId,
            currentProjectId: this.command.currentProjectId,
            majorName: this.majorForm.majorName,
            output: this.majorForm.output,
            masterUid: this.majorForm.masterUid,
            participants: this.majorForm.participants
          }
        ],
        domain = [this.$store.state.DOMAIN],
        path = ['/project/structure/createMajor'],
        dataAxios = this.$tools.getDataAxios(this, domain, path, data)
      Promise.all(dataAxios)
        .then((response) => {
          this.$tools.callbackAxios(this, response, (response) => {
            var data = response[0].data
            if (data.code === 200) {
              this.$message({
                message: data.message,
                type: 'success',
                duration: '1000',
                onClose: () => {
                  this.loading.major = false
                  this.dialogVisible.major = false
                  var org = data.data
                  this.org = this.setOrg(org)
                }
              })
            } else {
              this.$message({
                message: data.message,
                type: 'warning',
                duration: '1000',
                onClose: () => {
                  this.loading.major = false
                }
              })
            }
          })
        })
        .catch((error) => {})
    },
    //编辑专业
    editMajor() {
      var data = [
          {
            userId: this.uid,
            rootProjectId: this.rootProjectId,
            currentProjectId: this.command.currentProjectId,
            majorName: this.majorForm.majorName,
            output: this.majorForm.output,
            masterUid: this.majorForm.masterUid,
            participants: this.majorForm.participants
          }
        ],
        domain = [this.$store.state.DOMAIN],
        path = ['/project/structure/editMajor'],
        dataAxios = this.$tools.getDataAxios(this, domain, path, data)
      Promise.all(dataAxios)
        .then((response) => {
          this.$tools.callbackAxios(this, response, (response) => {
            var data = response[0].data
            if (data.code === 200) {
              this.$message({
                message: data.message,
                type: 'success',
                duration: '1000',
                onClose: () => {
                  this.loading.major = false
                  this.dialogVisible.major = false
                  var org = data.data
                  this.org = this.setOrg(org)
                }
              })
            } else {
              this.$message({
                message: data.message,
                type: 'warning',
                duration: '1000',
                onClose: () => {
                  this.loading.major = false
                }
              })
            }
          })
        })
        .catch((error) => {})
    },
    //判断某个节点的 所有子节点是否统一关闭或打开
    deepFind(nodes) {
      if (nodes.children.length) {
        var isAllSlide = false,
          isAllNotSlide = false

        isAllSlide = nodes.children.every((item) => {
          return (item.isSlide || item.cardType === 5) && (item.children.length ? this.deepFind(item).isAllSlide : true)
        })

        isAllNotSlide = nodes.children.every((item) => {
          return (!item.isSlide || item.cardType === 5) && (item.children.length ? this.deepFind(item).isAllNotSlide : true)
        })
        if (isAllSlide) {
          nodes.isChildrenSlide = true
        }
        if (isAllNotSlide) {
          nodes.isChildrenSlide = false
        }
        return { isAllSlide: isAllSlide, isAllNotSlide: isAllNotSlide }
      }
    },
    //单个节点展开 收缩
    toogleSlide(nodes) {
      nodes.isSlide = !nodes.isSlide
      nodes.top = nodes.isSlide ? 25 : 60
      //追溯一条线是否全部开 或者关
      this.deepFind(this.org)
    },
    //所有子节点展开 收缩
    toogleChildrenSlide(nodes) {
      nodes.isChildrenSlide = !nodes.isChildrenSlide
      function deepSet(node) {
        if (node.children.length) {
          node.children.forEach((item) => {
            if (item.cardType !== 5) {
              item.top = nodes.isChildrenSlide ? 25 : 60
              item.isSlide = nodes.isChildrenSlide
              item.isChildrenSlide = nodes.isChildrenSlide
              deepSet(item)
            }
          })
        }
      }
      deepSet(nodes)
    },
    //获取卡片剩余产值
    getResidueValue(currentProjectId) {
      var data = [{ userId: this.uid, currentProjectId: currentProjectId }],
        domain = [this.$store.state.DOMAIN],
        path = ['/project/structure/queryResidueOutputBeforeCreateCard'],
        dataAxios = this.$tools.getDataAxios(this, domain, path, data)
      Promise.all(dataAxios)
        .then((response) => {
          this.$tools.callbackAxios(this, response, (response) => {
            var data = response[0].data
            if (data.code === 200) {
              //开始创建前 重置表单
              this.dialogVisible[this.command.type] = true
              if (this.command.type === 'manager') {
                this.managerForm.isEdit = false
                this.managerForm.manageUnitName = ''
                this.managerForm.residueOutput = data.data.residueOutput
                this.managerForm.output = ''
                this.managerForm.masterUid = ''
                this.optManager.selectedUserList = []

                // setTimeout(() => {
                // this.$refs.managerSelectUser.resetSelectUser()
                this.$nextTick(() => {
                  this.$refs.managerForm.clearValidate()
                })
                //  }, 100)
              } else if (this.command.type === 'cooperate') {
                this.cooperateForm.isEdit = false
                this.cooperateForm.cooperationUnitName = ''
                this.cooperateForm.residueOutput = data.data.residueOutput
                this.cooperateForm.output = ''
                this.cooperateForm.masterUid = ''
                this.optCooprate.selectedUserList = []

                //  setTimeout(() => {
                // this.$refs.cooperateSelectUser.resetSelectUser()
                this.$nextTick(() => {
                  this.$refs.cooperateForm.clearValidate()
                })
                //}, 100)
              } else if (this.command.type === 'major') {
                this.majorForm.isEdit = false
                this.majorForm.majorName = ''
                this.majorForm.residueOutput = data.data.residueOutput
                this.majorForm.output = ''
                this.majorForm.masterUid = ''
                this.majorForm.participants = ''
                this.optMajorMaster.selectedUserList = []
                this.optMajorParter.selectedUserList = []

                // setTimeout(() => {
                //  this.$refs.majorMasterSelectUser.resetSelectUser()
                // this.$refs.majorParterSelectUser.resetSelectUser()
                this.$nextTick(() => {
                  this.$refs.majorForm.clearValidate()
                })
                // }, 100)
              }
            } else {
              this.$message({
                message: data.message,
                type: 'warning',
                duration: '1000',
                onClose: () => {}
              })
            }
          })
        })
        .catch((error) => {})
    },
    //获取卡片信息
    getCardInfo(projectId) {
      var data = [{ userId: this.uid, projectId: projectId }],
        domain = [this.$store.state.DOMAIN],
        path = ['/project/structure/cardInfo'],
        dataAxios = this.$tools.getDataAxios(this, domain, path, data)
      Promise.all(dataAxios)
        .then((response) => {
          this.$tools.callbackAxios(this, response, (response) => {
            var data = response[0].data
            if (data.code === 200) {
              var cardType = data.data.cardType
              //将createForm 转为 editForm

              //开始编辑前 重置表单
              if (cardType === 2) {
                this.dialogVisible.manager = true
                this.managerForm.isEdit = true
                this.managerForm.manageUnitName = data.data.projectName
                this.managerForm.residueOutput = data.data.upperResidueOutput
                this.managerForm.output = data.data.output
                //编辑管理单位 已选负责人列表
                this.optManager.selectedUserList = data.data.master
                this.managerForm.masterUid = data.data.master
                  .map((item) => {
                    return item.userId
                  })
                  .join()
                //  setTimeout(() => {
                // this.$refs.managerSelectUser.resetSelectUser()
                this.$nextTick(() => {
                  this.$refs.managerForm.clearValidate()
                })
                //}, 100)
              } else if (cardType === 3) {
                this.dialogVisible.cooperate = true
                this.cooperateForm.isEdit = true
                this.cooperateForm.cooperationUnitName = data.data.projectName
                this.cooperateForm.residueOutput = data.data.upperResidueOutput
                this.cooperateForm.output = data.data.output
                //编辑合作单位 已选负责人列表
                this.optCooprate.selectedUserList = data.data.master
                this.cooperateForm.masterUid = data.data.master
                  .map((item) => {
                    return item.userId
                  })
                  .join()
                // setTimeout(() => {
                //  this.$refs.cooperateSelectUser.resetSelectUser()
                this.$nextTick(() => {
                  this.$refs.cooperateForm.clearValidate()
                })
                // }, 100)
              } else if (cardType === 4) {
                this.dialogVisible.major = true
                this.majorForm.isEdit = true
                this.majorForm.majorName = data.data.projectName
                this.majorForm.residueOutput = data.data.upperResidueOutput
                this.majorForm.output = data.data.output
                //编辑专业 已选负责人列表
                this.optMajorMaster.selectedUserList = data.data.master.filter((item) => {
                  return item.masterState === 1
                })
                this.majorForm.masterUid = this.optMajorMaster.selectedUserList
                  .map((item) => {
                    return item.userId
                  })
                  .join()
                // setTimeout(() => {
                // this.$refs.majorMasterSelectUser.resetSelectUser()
                this.$nextTick(() => {
                  this.$refs.majorForm.clearValidate()
                })
                //  }, 100)

                //编辑专业 已选参与人列表
                this.optMajorParter.selectedUserList = data.data.master.filter((item) => {
                  return item.masterState === 0
                })
                this.majorForm.participants = this.optMajorParter.selectedUserList
                  .map((item) => {
                    return item.userId
                  })
                  .join()

                //  setTimeout(() => {
                // this.$refs.majorParterSelectUser.resetSelectUser()
                this.$nextTick(() => {
                  this.$refs.majorForm.clearValidate()
                })
                //  }, 100)
              }
            } else {
              this.$message({
                message: data.message,
                type: 'warning',
                duration: '1000',
                onClose: () => {}
              })
            }
          })
        })
        .catch((error) => {})
    },
    //删除卡片
    deleteCard(currentProjectId) {
      var data = [{ userId: this.uid, rootProjectId: this.rootProjectId, currentProjectId: currentProjectId }],
        domain = [this.$store.state.DOMAIN],
        path = ['/project/structure/deleteCard'],
        dataAxios = this.$tools.getDataAxios(this, domain, path, data)
      Promise.all(dataAxios)
        .then((response) => {
          this.$tools.callbackAxios(this, response, (response) => {
            var data = response[0].data
            if (data.code === 200) {
              var org = data.data
              this.org = this.setOrg(org)
              // setTimeout(() => {
              //   this.$refs.orgTree.drawVerLine()
              // }, 100)
            } else {
              this.$message({
                message: data.message,
                type: 'warning',
                duration: '1000',
                onClose: () => {}
              })
            }
          })
        })
        .catch((error) => {})
    },
    //显示任务抽屉
    showTask(nodes) {
      this.task.showOutput = nodes.showOutput //是否显示
      this.task.nodes = nodes
      this.getTaskLis(1)
    },
    getTaskLis(page) {
      var data = [
          {
            userId: this.uid,
            rootProjectId: this.rootProjectId,
            majorId: this.task.nodes.parentId,
            masterUid: this.task.nodes.majorUserUid,
            page: page,
            pageSize: 20
          }
        ],
        domain = [this.$store.state.DOMAIN],
        path = ['/project/task/taskStat'],
        dataAxios = this.$tools.getDataAxios(this, domain, path, data)
      Promise.all(dataAxios)
        .then((response) => {
          this.$tools.callbackAxios(this, response, (response) => {
            var data = response[0].data
            if (data.code === 200) {
              this.dialogVisible.task = true
              this.task.list = data.data.list
              this.task.totalCount = data.data.totalCount
              this.task.doingCount = data.data.doingCount
              this.task.complateCount = data.data.complateCount
              this.task.waitCount = data.data.waitCount
              this.task.delayCount = data.data.delayCount
              this.task.totalOutput = data.data.totalOutput
            } else {
              this.$message({
                message: data.message,
                type: 'warning',
                duration: '1000',
                onClose: () => {}
              })
            }
          })
        })
        .catch((error) => {})
    },
    //任务抽屉翻页
    handleCurrentChange(page) {
      this.getTaskLis(page)
    },
    tableRowClassName({ row, rowIndex }) {
      if (row.completeState < 0) {
        return 'postpone-row'
      }
      if (row.completeState > 0) {
        return 'advance-row'
      }
    },
    //上一步创建项目
    goCreatePm() {
      if (this.rootProjectId) {
        this.$router.push('/main/#/pm?tab=create&elTab=0&rootProjectId=' + this.rootProjectId)
      } else {
        this.$router.push('/main/#/pm?tab=create&elTab=0')
      }
    },
    //下一步创建项目节点
    goCreateNode() {
      this.$router.push('/main/#/pm?tab=create&elTab=2&rootProjectId=' + this.rootProjectId)
    }
  },
  mounted() {
    //加载组织架构数据
    this.getOrg(this.query.rootProjectId)
    //加载企业人员列表
    this.getCompanyUserList()
  }
}
</script>
<style scoped>
.dt-content-page {
  background-color: transparent;
}
/**生产任务统计抽屉**/
.el-drawer__wrapper >>> .el-drawer {
  padding: 18px 20px;
}
.el-drawer__wrapper >>> .dt-el-drawer {
  font-size: 12px;
  margin-bottom: 20px;
}
.el-drawer__wrapper >>> .dt-el-drawer span {
  color: #606266;
  margin-right: 20px;
}
.el-drawer__wrapper >>> .dt-el-drawer em {
  margin-right: 20px;
  color: #e9eef7;
}
.el-drawer__wrapper >>> .el-table th.el-table__cell {
  background-color: #fafafa;
}
.el-drawer__wrapper >>> .el-drawer__header {
  margin-bottom: 20px;
  padding: 0;
  font-size: 18px;
  color: #1f1f1f;
}

.el-drawer__wrapper >>> .el-drawer__body {
  display: flex;
  flex-direction: column;
}
.el-table {
  font-size: 12px;
  color: #1f1f1f;
}
.el-table >>> .el-table__cell {
  padding: 0;
  height: 50px;
}
.el-table >>> .el-table__cell .cell {
  line-height: 1.5;
  padding: 10px;
}
.dt-drawer-table {
  flex: 1;
}
/**组织架构**/

/**三个添加单位form**/
.el-dialog__wrapper >>> .el-dialog__header {
  padding: 18px 20px 16px;
}
.el-dialog__wrapper >>> .el-dialog__body {
  padding: 0 20px 16px;
}
.el-dialog__wrapper >>> .el-form-item__label {
  text-align: left;
}
.el-dialog__wrapper >>> .el-form .el-form-item:nth-last-child(1) {
  text-align: right;
  padding: 16px 20px 0 20px;
  border-top: 1px solid #e9eef7;
  margin: 0 -20px;
}
.dt-je-china {
  top: 0;
  right: 65px;
  color: #909399;
}
</style>